<?php

namespace Bigspender\DefaultBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Bigspender\DefaultBundle\Form\LoginType;
use Symfony\Component\Security\Core\SecurityContext;

class UserController extends Controller
{
    public function loginAction(Request $request)
    {
        $session = $request->getSession();

        if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
            $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
        } 
        else {
            $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
            $session->remove(SecurityContext::AUTHENTICATION_ERROR);
        }

        if ($error) {
            $this->get('session')->getFlashBag()->setName('error');
            $message = $error->getMessage();
            $this->get('session')->getFlashBag()->add('message', $this->get('translator')->trans($message));
        }

        $lastUsername = $session->get(SecurityContext::LAST_USERNAME);
        $form = $this->createForm(new LoginType($lastUsername), null, array('action' => $this->generateUrl('_login_check')));
        return $this->render('BigspenderDefaultBundle:User:login.html.twig', array('form' => $form->createView()));
    }

    /**
     * @Route("/activate/{hash}", name="user_sign_up")
     * @Template()
     */
    public function signUpAction(Request $request)
    {
        $hash = $request->get('hash');
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('Bigspender\DefaultBundle\Entity\User')->findOneBy(array('hash' => $hash));

        $flashBag = $this->get('session')->getFlashBag();
        $translator = $this->get('translator');
        
        if (count($user)) {
            $user->activate();
            $em->persist($user);
            $em->flush();

            $flashBag->setName('success');
            $flashBag->add('message', $translator->trans('ACTIVATE SUCCESS'));
        }
        else {
            $flashBag->setName('error');
            $flashBag->add('message', $translator->trans('ACTIVATE NO USER ERROR'));
        }

        return $this->redirect($this->generateUrl('_login'));
    }

    /**
     * @Route("/recover-password", name="user_recover_password")
     * @Template()
     */
    public function recoverPasswordAction(Request $request)
    {
        
    }

    /**
     * @Route("/edit", name="user_edit")
     * @Template()
     */
    public function editAction(Request $request)
    {
        
    }
}
